import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:kxy_flutter_app/model/home.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:kxy_flutter_app/view/home/nav_route.dart';
import 'package:smooth_page_indicator/smooth_page_indicator.dart';

class HomeBannerWidget extends StatelessWidget {
  final List<HomeBanner> bannerList;

  HomeBannerWidget({@required this.bannerList});

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Builder(
        builder: (BuildContext context) {
          if (bannerList.length == 0) {
            return Container();
          } else {
            return createSwiper(bannerList, context);
          }
        },
      ),
      height: MediaQuery.of(context).size.width / 2,
    );
  }

  Widget createSwiper(List<HomeBanner> bannerList, BuildContext context) {
    return Swiper(
      key: Key('swiper_key_${bannerList.length}'),
      itemBuilder: (BuildContext context, int index) {
        var item = bannerList[index];
        return Container(
          padding: EdgeInsets.symmetric(horizontal: 10),
          child: bannerItem(item, context),
        );
      },
      itemCount: bannerList.length,
      pagination: SwiperCustomPagination(builder: (cxt, config) {
        return Positioned(
          child: pageIndicator(config.pageController, context),
          bottom: 10,
          right: 30,
        );
      }),
      loop: true,
      autoplay: true,
      autoplayDelay: 5000,
    );
  }

  Widget bannerItem(HomeBanner banner, BuildContext context) {
    return GestureDetector(
      child: ClipRRect(
        borderRadius: BorderRadius.circular(7),
        child: AspectRatio(
          aspectRatio: 16 / 9,
          child: CachedNetworkImage(
            imageUrl: banner.coverUrl,
            fit: BoxFit.cover,
          ),
        ),
      ),
      onTap: () {
        NavRoute.pushTo(banner.modulePath, context, param: banner.params);
      },
    );
  }

  Widget pageIndicator(PageController controller, BuildContext context) {
    return SmoothPageIndicator(
      controller: controller,
      count: bannerList.length,
      effect: WormEffect(
        dotWidth: 7,
        dotHeight: 7,
        dotColor: Color.fromRGBO(220, 220, 220, 1),
        activeDotColor: Theme.of(context).primaryColor,
      ),
    );
  }
}
